package com.tbs.easyhomemoneyserver.model.rights

import com.tbs.easyhomemoneyserver.DO.ApiLimit
import com.tbs.easyhomemoneyserver.DO.UserRights
import java.io.Serializable
import java.util.*
import java.util.stream.Collectors

class UserRightTable(limits: List<ApiLimit>, rights: List<UserRights>) : Serializable {
    /**
     *  从外到里的key分别对应roleType role url 对应到数据库中刚好是唯一的权限
     */
    private val m_rightsMap = HashMap<Int, MutableMap<String, MutableMap<String, UserRights>>>()

    private var m_roleType: Int? = null
    private var m_role: String? = null
    private var m_url: String? = null

    init {
        val rightsMap = rights.stream().collect(Collectors.toMap(UserRights::rightsId) { r: UserRights -> r })
        for (i in limits) {
            if (i.roleType == null || i.role == null || i.id == null || i.url == null) continue
            val typeMap = m_rightsMap.getOrDefault(i.roleType, HashMap())
            val roleMap = typeMap.getOrDefault(i.role, HashMap())
            val r = rightsMap[i.id]
            if (r != null) {
                roleMap[i.url!!] = r;
            }
            typeMap[i.role!!] = roleMap
            m_rightsMap[i.roleType!!] = typeMap
        }
    }

    fun indexRoleType(roleType: Int?): UserRightTable {
        m_roleType = roleType
        return this
    }

    fun indexRole(roleName: String?): UserRightTable {
        m_role = roleName
        return this
    }

    fun indexUrl(url: String?): UserRightTable {
        m_url = url
        return this
    }

    fun select(): List<UserRights> {
        val result = LinkedList<UserRights>()
        if (m_roleType == null) {
            for (i in m_rightsMap.values) {
                for (j in i.values) {
                    for (r in j.values) {
                        result.add(r)
                    }
                }
            }
            return result
        }
        if (m_role == null) {
            for (j in m_rightsMap.getOrDefault(m_roleType, HashMap()).values) {
                for (r in j.values) {
                    result.add(r)
                }
            }
            return result
        }
        if (m_url == null) {
            for (r in m_rightsMap.getOrDefault(m_roleType, HashMap()).getOrDefault(m_role, HashMap()).values) {
                result.add(r)
            }
            return result
        }

        val v = m_rightsMap.getOrDefault(m_roleType, HashMap()).getOrDefault(m_role, HashMap())[m_url]
        if (v != null) {
            result.add(v);
        }
        return result
    }

    companion object {
        private val serialVersionUID = -8956048043174600609L
    }
}